package com.sdtele.tta.servlets;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;

import com.google.gson.Gson;
import com.sdtele.tta.dac.Dac;
import com.sdtele.tta.models.JsonResponse;
import com.sdtele.tta.models.User;

import sun.misc.BASE64Decoder;






@WebServlet("/UploadAvatar")
@MultipartConfig
public class UploadAvatar extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}
  /*  private String getFilename(Part part) {
        String contentDispositionHeader = 
                part.getHeader("content-disposition");
        String[] elements = contentDispositionHeader.split(";");
        for (String element : elements) {
            if (element.trim().startsWith("filename")) {
                String fileName = element.substring(element.indexOf('=') + 1)
                        .trim().replace("\"", "");
                return new File(fileName).getName();
            }
        }
        return null;
    }
    */
    
	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		Gson gson=new Gson();
		Map<String, String> inputMap = new HashMap<String, String>();
		Map<String, String> errorMap = new HashMap<String, String>();
		request.setAttribute("input", inputMap);
		request.setAttribute("error", errorMap);
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		JsonResponse jres = new JsonResponse();
		User user = (User)request.getSession().getAttribute("user");
		System.out.println("当前用户请求："+request);
		System.out.println("当前用户信息："+user);
		//	User user = Dac.getInstance().getUser(0);
		if(user != null)
		{
			
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String uriPath = "Avatars/"+sdf.format(new Date());
		String physicalPath = getServletContext().getRealPath(uriPath);
		if(! new File(physicalPath).exists()) {
			new File(physicalPath).mkdirs();
		}
		physicalPath += File.separator;
		String fn = UUID.randomUUID().toString();
		physicalPath += fn+ ".png";
		uriPath += "/"+ fn+ ".png";
		
		System.out.println(physicalPath);
		System.out.println(uriPath);
		boolean success = false;
		String imgStr=request.getParameter("image");
		
		if(imgStr!=null)
		{
			String byteStr=imgStr.split(",")[1];

		if(GenerateImage(byteStr,physicalPath))
		{
			success = true ;
			System.out.println(byteStr);
			if((user.getAvatar().equals("Avatars/male"))||(user.getAvatar().equals("Avatars/female")))
			{
				user.setAvatar(uriPath);
				Dac.getInstance().chgUser(user);
				response.getWriter().append("存储成功");
				
				System.out.println("执行更新");
			}else
			{
				//删除相关文件
				String oldPath=getServletContext().getRealPath(user.getAvatar());
			     File oldAvatar = new File(oldPath);
	//		     System.out.println("原有文件路径"+oldPath);
			     if(oldAvatar.exists())
			     { 
			    	 oldAvatar.delete();
			//     System.out.println("构建文件失败");
			     }
			     
			     //更新数据库
				user.setAvatar(uriPath);
				Dac.getInstance().chgUser(user);
				
		//		System.out.println("执行更新+删除文件");
				
			}
			
			jres.setStatus(0);
			jres.setMessage("头像修改成功");
			
		}else{
				errorMap.put("Error", "存储失败");
				jres.setStatus(1);
				jres.setMessage("头像修改失败");
			
			}
			}
	
		}else
		{
			errorMap.put("Error", "用户不在有效期");
			jres.setStatus(1);
			jres.setMessage("头像修改失败");
		}
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().append(gson.toJson(jres));
		
	}
	
	
	
	
    public static boolean GenerateImage(String imgStr,String patch)  
    {   //对字节数组字符串进行Base64解码并生成图片  
        if (imgStr == null) //图像数据为空  
        {   System.out.println("错误提示");
        	
        	return false;  }
        BASE64Decoder decoder = new BASE64Decoder();  
        try   
        {  
            //Base64解码  
            byte[] b = decoder.decodeBuffer(imgStr);  
            for(int i=0;i<b.length;++i)  
            {  
                if(b[i]<0)  
                {//调整异常数据  
                    b[i]+=256;  
                }  
            }  
            System.out.print(b);
            //生成jpeg图片 
            String imgFilePath = patch;//新生成的图片  
            OutputStream out = new FileOutputStream(imgFilePath);      
            out.write(b);  
            out.flush();  
            out.close();  
            return true;  
        }   
        catch (Exception e)   
        {  
            e.printStackTrace();
        	return false;  
        }  
    } 
      
}


